package com.itheima.reggie.controller;

import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.common.SmsTemplate;
import com.itheima.reggie.domain.User;
import com.itheima.reggie.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;

//进店客户
@RestController
public class UserController {
    @Autowired
    private HttpSession httpSession;

    @Autowired
    private SmsTemplate smsTemplate;

    @Autowired
    private UserService userService;

    //发送短信验证
    @PostMapping("/user/sendMsg")//@RequestBody只能接收map或者对象
    public ResultInfo sendMsg(@RequestBody Map<String, String> map) {

        //1. 接收参数
        String phone = map.get("phone");

        //2. 生成验证码
        //String code = RandomUtil.randomNumbers(6);
        //TODO 写死一个验证码为123 为了测试方便
        String code = "123";

        //3. 验证码保存到session中
        httpSession.setAttribute("SMS_" + phone, code);

        //4. 发送验证码到手机 TODO 目前无法使用
        //smsTemplate.sendSms(phone,code);

        return ResultInfo.success(null);
    }

    //注册登录
    @PostMapping("/user/login")
    public ResultInfo login(@RequestBody Map<String, String> map) {
        //1. 接收参数
        String phone = map.get("phone");
        String code = map.get("code");

        //2. 校验code   前端传入code  ==  session中保存的code
        String codeFromSession = (String) httpSession.getAttribute("SMS_" + phone);
        if (!StringUtils.equals(code, codeFromSession) ||
                StringUtils.isEmpty(code) ||
                StringUtils.isEmpty(codeFromSession)) {
            return ResultInfo.error("验证码有误!");
        }

        //3. 根据phone从数据库中查询
        User user = userService.findByPhone(phone);

        if (user != null){
            //能从数据库中查询到用户:老用户登录
        }else {
            //不能从数据库中查询到用户:新用户注册
            user = new User();// !!! 注意空指针  此时的user为null
            user.setStatus(1);//正常状态
            user.setPhone(phone);
            userService.save(user);//注册:将用户信息保存至数据库中
        }
        //4. 将user信息保存到session中 (注意: 这个键必须跟拦截器中使用的键一致)
        httpSession.setAttribute("SESSION_USER",user);//登录

        //5. 返回成功标识
        return ResultInfo.success(user);
    }

    //退出登录
    @PostMapping("/user/logout")
    public ResultInfo logout() {
        //httpSession.removeAttribute("SESSION_USER");

        //注销session
        httpSession.invalidate();

        return ResultInfo.success(null);
    }
}
